package com.rwb.springboot.sell.service.impl;

import com.rwb.springboot.sell.dto.OrderDTO;
import com.rwb.springboot.sell.enums.ResultEnum;
import com.rwb.springboot.sell.exception.MallException;
import com.rwb.springboot.sell.service.BuyerService;
import com.rwb.springboot.sell.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by ruwenbo on 2018/1/3.
 */
@Service("buyerService")
public class BuyerServiceImpl implements BuyerService{

    private static final Logger LOGGER = LoggerFactory.getLogger(BuyerServiceImpl.class);

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid, orderId);
    }

    @Override
    public OrderDTO cancel(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        if (orderDTO == null) {
            LOGGER.error("【取消订单】查不到该订单,openid={}", openid);
            throw new MallException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    private OrderDTO checkOrderOwner(String openid, String orderId) {
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            return null;
        }
        // 判断是否是自己的订单
        if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)) {
            LOGGER.error("【查询订单】订单的openid不一致,openid={},orderDTO={}", openid, orderDTO);
            throw new MallException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
